﻿using Microsoft.SharePoint.WebPartPages;
using RoketSolutions.SP2010.Infrostructure.Localization;
using RoketSolutions.SP2010.Infrostructure.UI.Controls.Interfaces;
using RoketSolutions.SP2010.Infrostructure.UI.WebParts.Interfaces;

namespace RoketSolutions.SP2010.Infrostructure.UI.WebParts.ToolParts
{
    public class LocalizationToolPart : ToolPart
    {
        const string ToolPartControlUrl = @"~/_controltemplates/RoketSolutions.SP2010.Infrostructure/LocalizationToolPartControl.ascx";

        #region / Constructor /

        public LocalizationToolPart(LocalizationSettings settings)
        {
            Settings = settings;
        }

        #endregion

        #region / Properties /

        private LocalizationSettings Settings { get; set; }

        private IToolPartControl<LocalizationSettings> TargetControl { get; set; }

        #endregion

        #region / Overriden Methods /

        protected override void OnInit(System.EventArgs e)
        {
            EnsureChildControls();
            base.OnInit(e);
        }

        protected override void OnLoad(System.EventArgs e)
        {
            if (TargetControl != null)
            {
                TargetControl.Initialize(Settings);
            }
            base.OnLoad(e);
        }

        protected override void CreateChildControls()
        {
            if (TargetControl == null)
            {
                TargetControl = Page.LoadControl(ToolPartControlUrl) as IToolPartControl<LocalizationSettings>;
                if (TargetControl != null)
                {
                    Controls.Add(TargetControl.Control);
                }
                base.CreateChildControls();
            }
        }

        public override void ApplyChanges()
        {
            var webpart = ParentToolPane.SelectedWebPart as ILocalizableWebPart;
            if (webpart != null && TargetControl != null)
            {
                // save changes
                webpart.ApplySettings(TargetControl.SaveData());
            }
        }

        #endregion


    }
}